﻿using AutoMapper.Execution;
using AutoMapper.Internal.Mappers;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using SMARTHOTEL.hotel;
using SMARTHOTEL.Products;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;
using static OpenIddict.Abstractions.OpenIddictConstants;

namespace SMARTHOTEL.RoomNum
{

    /// <summary>
    /// 房号管理
    /// </summary>
    [ApiExplorerSettings(GroupName = "v2")]
    public class RoomNumService : ApplicationService, IRoomNumService
    {
        IRepository<RoomNumber> roomRep;

        IRepository<RoomType> roomtyp;


        public RoomNumService(IRepository<RoomNumber> roomRep, IRepository<RoomType> roomtyp)
        {
            this.roomRep = roomRep;
            this.roomtyp = roomtyp;
        }
        /// <summary>
        /// 添加房号
        /// </summary>
        /// <param name="roomNumDto"></param>
        /// <returns></returns>
        [HttpPost("CreateAllAsyncs")]
        public async Task<ResultDto<bool>> CreateAllAsync(CreateUpdateRoomNumDto roomNumDto)
        {
            try
            {
                var roomTypeList = (await roomtyp.GetListAsync()).FirstOrDefault(m => m.Id == roomNumDto.RoomTypeId);

                RoomNumber roomnum = ObjectMapper.Map<CreateUpdateRoomNumDto, RoomNumber>(roomNumDto);
                
                roomnum.RoomTypeId = roomTypeList.Id;
                var roomnumList=await roomRep.FirstOrDefaultAsync(x=>x.RoomNum==roomNumDto.RoomNum);
                if (roomnumList != null)
                {
                    return new ResultDto<bool> { Data = false, Code = StatusCode.Faield, Msg = "房号已存在！" };
                }
                await roomRep.InsertAsync(roomnum);

                return new ResultDto<bool> { Data = true, Code = StatusCode.Success, Msg = "添加成功" };
            }
            catch (Exception ex)
            {
                return new ResultDto<bool> { Data = false, Code = StatusCode.Faield, Msg = "添加失败" + ex.Message };
            }
        }
        /// <summary>
        /// 显示所有房号和房型名称
        /// </summary>
        /// <param name="roomTypeName"></param>
        /// <param name="roomNum"></param>
        /// <returns></returns>
        [HttpGet("GetAllAsyncs")]
        public Task<ResultDto<List<RoomNumDto>>> GetAllAsync(string? roomTypeName, string? roomNum, bool? roomNumberStatues)
        {
            var list = from a in roomRep.GetQueryableAsync().Result
                       join b in roomtyp.GetQueryableAsync().Result on a.RoomTypeId equals b.Id
                       where a.IsDeleted == false
                       select new RoomNumDto
                       {
                           Id=a.Id,
                           RoomTypeId = b.Id,
                           RoomTypeName = b.RoomTypeName,
                           RoomNum = a.RoomNum,
                           Sort = a.Sort,
                           Remark = a.Remark,
                           RoomNumberStatues = a.RoomNumberStatues,
                           IsDeleted = a.IsDeleted
                       };
            if (!string.IsNullOrEmpty(roomTypeName))
            {
                list = list.Where(a => a.RoomTypeName.Contains(roomTypeName));
            }
            if (!string.IsNullOrEmpty(roomNum))
            {
                list = list.Where(a => a.RoomNum.Contains(roomNum));
            }
            if (roomNumberStatues != null)
            {
                list = list.Where(x => x.RoomNumberStatues == roomNumberStatues);
            }
            return Task.FromResult(new ResultDto<List<RoomNumDto>> { Data = list.ToList(), Code = StatusCode.Success, Msg = "查询成功" });
        }
        /// <summary>
        /// 单个修改房号状态（也可以单个修改上架下架）
        /// </summary>
        /// <returns></returns>
        [HttpPut("UpdateOneStateAsyncs")]
        public async Task<ResultDto<bool>> UpdateOneStateAsync(string Id)
        {
            try
            {
                var roomnum = await roomRep.GetAsync(x => x.Id == Guid.Parse(Id));
                if (roomnum == null)
                {
                    return new ResultDto<bool> {Data=false, Code = StatusCode.Faield, Msg = "修改失败，该数据不存在！" };
                }
                roomnum.RoomNumberStatues = !roomnum.RoomNumberStatues;
                await roomRep.UpdateAsync(roomnum);
                return new ResultDto<bool> { Data = true, Code = StatusCode.Success, Msg = "修改成功！" };
            }
            catch (Exception ex)
            {
                return new ResultDto<bool> { Data=false, Code = StatusCode.Faield,Msg="修改失败"+ex.Message};
            }
        }
        /// <summary>
        /// 批量修改房间类型（也可以批量修改上架下架）
        /// </summary>
        /// <returns></returns>
        [HttpPut("UpdateStateAsyncs")]
        public async Task<ResultDto<bool>> UpdateStateAsync(string Id, int state)
        {
            try
            {
                int i = 0;
                var ids = Id.Split(',');
                foreach (var item in ids)
                {
                    var roomtype = await roomRep.GetAsync(x => x.Id == Guid.Parse(item));
                    if (roomtype == null)
                    {
                        continue;
                    }
                    else
                    {
                        roomtype.RoomNumberStatues = Convert.ToBoolean(state);
                        await roomRep.UpdateAsync(roomtype);
                    }
                    i++;
                }
                return new ResultDto<bool> { Data = true, Code = StatusCode.Success, Msg = "修改成功" };
            }
            catch (Exception ex)
            {
                return new ResultDto<bool> { Data = false, Code = StatusCode.Faield, Msg = "修改失败" + ex.Message };
            }
        }
        /// <summary>
        /// 批量删除房间类型（也可以单个删除）
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete("DeleteAllAsyncs")]
        public async Task<ResultDto<bool>> DeleteAllAsync(string Id)
        {
            try
            {
                var ids = Id.Split(",");
                foreach (var item in ids)
                {
                    var roomtype = await roomRep.GetAsync(x => x.Id == Guid.Parse(item));
                    if (roomtype != null)
                    {
                        await roomRep.DeleteAsync(roomtype);
                    }
                }
                return new ResultDto<bool> { Data = false, Code = StatusCode.Success, Msg = "删除成功" };

            }
            catch (Exception ex)
            {
                return new ResultDto<bool> { Data = false, Code = StatusCode.Faield, Msg = "删除失败" + ex.Message };
            }
        }
        /// <summary>
        /// 单个删除房号
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete("DeleteOneAsyncs")]
        public async Task<ResultDto<bool>> DeleteOneAsync(string Id)
        {
            try
            {
                var roomnum = await roomRep.GetAsync(x => x.Id == Guid.Parse(Id));
                if (roomnum == null)
                {
                    return new ResultDto<bool> { Data = false, Code = StatusCode.Faield, Msg = "删除失败，该房号不存在！" };
                }
                else
                {
                    await roomRep.DeleteAsync(roomnum);

                    return new ResultDto<bool> { Data = true, Code = StatusCode.Success, Msg = "删除成功" };
                }
            }
            catch (Exception ex)
            {
                return new ResultDto<bool> { Data = false, Code = StatusCode.Faield, Msg = "删除失败" + ex.Message };
            }
        }
        /// <summary>
        /// 修改房号
        /// </summary>
        /// <param name="roomNumDto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPut("UpdateAllAsyncs")]
        public async Task<ResultDto<bool>> UpdateAllAsync(CreateUpdateRoomNumDtos roomNumDto, Guid id)
        {
            try
            {
                //根据房型名称找到对应的房型Id
                var roomTypeone = await roomtyp.FirstOrDefaultAsync(m => m.RoomTypeName == roomNumDto.RoomTypeName);

                //要修改的实体
                var roomnumone = await roomRep.GetAsync(x => x.Id == id);

                RoomNumber roomnum = ObjectMapper.Map<CreateUpdateRoomNumDtos, RoomNumber>(roomNumDto, roomnumone);

                //通过更改后的房型名称找到的房型Id赋给房号表里的房型Id
                roomnum.RoomTypeId = roomTypeone.Id;

                await roomRep.UpdateAsync(roomnum);

                return new ResultDto<bool> { Data = true, Code = StatusCode.Success, Msg = "修改成功" };
            }
            catch (Exception ex)
            {
                return new ResultDto<bool> { Data = false, Code = StatusCode.Faield, Msg = "修改失败" + ex.Message };
            }
        }
        
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public async Task<ResultDto<ActionResult>> ImportExcel(IFormFile file)
        {
            try
            {
                if (file == null || file.Length == 0)
                {
                    return new ResultDto<ActionResult> { Data = (ActionResult)file, Code = StatusCode.Faield, Msg = "导入失败" + "未提供有效的文件" };
                }

                using (MemoryStream ms = new MemoryStream())
                {
                    await file.CopyToAsync(ms);
                    ms.Position = 0;

                    using (IWorkbook wb = new XSSFWorkbook(ms))
                    {
                        ISheet sheet = wb.GetSheetAt(0);
                        int totalRows = sheet.LastRowNum;
                        if (totalRows == 0)
                        {
                            return new ResultDto<ActionResult> { Data = (ActionResult)file, Code = StatusCode.Faield, Msg = "导入失败" + "Excel 文件中没有数据。" };
                        }

                        int totalCells = sheet.GetRow(0).LastCellNum;
                        List<RoomNumber> list = new List<RoomNumber>();

                        for (int i = 1; i <= totalRows; i++)
                        {
                            IRow row = sheet.GetRow(i);
                            if (row == null)
                            {
                                continue;
                            }


                            ICell idCell = row.GetCell(0);
                            ICell nameCell = row.GetCell(1);
                            ICell typeIdCell = row.GetCell(2);
                            ICell strCell = row.GetCell(3);
                            ICell bolCell = row.GetCell(4);

                            if (nameCell == null || typeIdCell == null)
                            {
                                continue;
                            }
                            string romtpname=idCell.ToString();
                            string roomnum = nameCell.ToString();
                            string sort = typeIdCell.ToString();
                            string remark = strCell.ToString();
                            bool roomnumberstatues = bolCell.BooleanCellValue;

                            var romtypelist = await roomtyp.FirstOrDefaultAsync(x => x.RoomTypeName == romtpname);
                            
                            RoomNumber member = new RoomNumber();
                            member = new RoomNumber
                            {
                                RoomTypeId=romtypelist.Id,
                                RoomNum=roomnum,
                                Sort=Convert.ToInt32(sort),
                                Remark =remark,
                                RoomNumberStatues=roomnumberstatues
                            };
                            list.Add(member);
                            await roomRep.InsertAsync(member);
                        }
                        // 就是批量添加list进数据库里
                        //foreach (RoomNumber item in list)
                        //{
                        //    await roomRep.InsertAsync(item);
                        //}
                        return new ResultDto<ActionResult> { Code = StatusCode.Success,Msg="上传成功！" };

                        /*int result = bll.PostAddHouseNoList(list);
                        return new ResultDto<ActionResult> { Data = result, Code = StatusCode.Success, Msg = "导入成功" };*/
                    }
                }
            }
            catch (Exception ex)
            {
                // 记录日志，这里可以使用日志框架，如 Serilog、NLog 等
                Console.WriteLine($"导入 Excel 文件时发生错误: {ex.Message}");
                return new ResultDto<ActionResult> { Data = (ActionResult)file, Code = StatusCode.Faield, Msg = "导入失败" + "服务器内部错误，请稍后重试。" };
            }
        }
    }
}
